﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace Petaframe.DataAccess
{

    /// <summary>
    /// SqlServer veritabanına ait işlemler için parametrelere ait bilgileri oluşturur.
    /// </summary>
    internal class SqlServerParameterBuilder:IParameterBuilder
    {
        //DbProviderFactory _providerFactory;
        //public SqlServerParameterBuilder()
        //{
        //    _providerFactory = DbProviderFactories.GetFactory("System.Data.SqlClient");
        //}

        public ParameterInfo CreateParameter(DbProviderFactory factory, int index, System.Reflection.PropertyInfo clazzProperty)
        {
            ParameterInfo pInfo = new ParameterInfo();

            var uniqueName = Guid.NewGuid().ToString().Substring(0, 7);
            pInfo.ParameterSimpleName = "p" + index;
            pInfo.ParameterUniqueName = "p"+uniqueName;
            pInfo.ParameterColumnName = clazzProperty.Name;
            pInfo.ParameterPosition = index;

            pInfo.DatabaseParameter = factory.CreateParameter();
            pInfo.DatabaseParameter.ParameterName = "@p" + index;


            //value tip mi?
            if (clazzProperty.PropertyType.IsValueType)
            {
                //Nullable tip mi?
                if (clazzProperty.PropertyType.IsGenericType)
                    pInfo.DatabaseParameter.DbType = TypeToDbType(Nullable.GetUnderlyingType(clazzProperty.PropertyType).Name);
                else
                    pInfo.DatabaseParameter.DbType = TypeToDbType(clazzProperty.PropertyType.Name);

            }
            else
                pInfo.DatabaseParameter.DbType = TypeToDbType(clazzProperty.PropertyType.Name);


            pInfo.DatabaseParameter.Size = DbTypeSize(clazzProperty.PropertyType.Name);

            return pInfo;
        }

     

        private static DbType TypeToDbType(string TypeName)
        {
            DbType dbt;
            try
            {
                if (TypeName == "Byte[]" )
                {
                    dbt = DbType.Binary;
                }
                else
                {
                    dbt = (DbType)Enum.Parse(typeof(DbType), TypeName);
                }
            }
            catch
            {
                dbt = DbType.Object;
            }
            return dbt;
        }

        private static int DbTypeSize(string TypeName)
        {
            switch (TypeName)
            {
                case "Byte[]":
                    return 4000;               
                case "String":
                    return 4000;

                default:
                    return 0;

            }
        }


     
    }
}
